package nl.hanze.designpatterns.DAO.impl.file.crypted;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import nl.hanze.designpatterns.DAO.impl.file.ser.FileSerialize;
import nl.hanze.designpatterns.domain.LoginCredential;

public class CryptedOutputStream {
	static String IV = "AAAAAAAAAAAAAAAA";
	static String encryptionKey = "0123456789abcdef";
	
	public CryptedOutputStream(LoginCredential lc) throws Exception{
		FileSerialize fs = new FileSerialize();
		System.out.println(lc.getUserName());
		lc.setUserName(encrypt(lc.getUserName(),encryptionKey));
		lc.setPassword(encrypt(lc.getPassword(),encryptionKey));
		System.out.println(lc.getUserName());
		System.out.println(lc.getPassword());
		fs.serialize(lc);
	}
		
	public byte[] getBytes(LoginCredential lc) throws java.io.IOException{
	      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
	      ObjectOutputStream oos = new ObjectOutputStream(bos); 
	      oos.writeObject(lc);
	      byte [] data = bos.toByteArray();
	      return data;
	  }
	
	 public static String encrypt(String plainText, String passkey) throws Exception {
	        Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
	        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
	        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
	        String cipherText = new String(cipher.doFinal(plainText.getBytes()));
	        return cipherText;
	    }
}
